/*
 * Created by: 
 * Created: December-03-07
 */

using System;
using System.Text;
using System.Xml;
using Kassandra.Core.Infrastructure.ResourceManagement;

namespace Kassandra.Core
{
    public interface IWordMlDocument
    {
        string ConvertDocument();
    }

    public class WordMlDocument : IWordMlDocument
    {
        private readonly ICustomWordWrapper wrapper;
        private XmlDocument sourceDocument = new XmlDocument();
        private XmlNode body;

        public WordMlDocument(string source) : this(source, new CustomWordWrapper(14))
        {
        }

        public WordMlDocument(string source, ICustomWordWrapper wrapper)
        {
            this.wrapper = wrapper;
            sourceDocument.LoadXml(source);
            XmlNodeList list = sourceDocument.GetElementsByTagName("w:body");
            if ((list == null) || (list.Count <= 0))
                throw new ApplicationException(MessageManagement.For("CouldNotLoadBodyElement"));
            body = list[0];
        }

        public string ConvertDocument()
        {
            EnumerateNodesAndPerformReplacements(body);
            return sourceDocument.OuterXml;
        }

        private void EnumerateNodesAndPerformReplacements(XmlNode node)
        {
            ReplaceTextWithImagesFor(node);
            foreach (XmlNode childNode in node.ChildNodes)
            {
                EnumerateNodesAndPerformReplacements(childNode);
            }
        }

        private void ReplaceTextWithImagesFor(XmlNode node)
        {
            if (node.InnerText.Trim().Length == 0)
                return;
            if (node.Name != "w:t")
                return;

            StringBuilder sb = new StringBuilder();
            foreach (string line in wrapper.WrapText(node.InnerText))
            {
                foreach (char c in line)
                {
                    sb.Append(ImageFactory.CreateFor(c));
                }
                sb.Append("<w:br />");
            }
           node.InnerXml = sb.ToString();
        }
    }
}